package com.general.template.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.general.template.dto.QuestionCommonDto;
import com.general.template.mapper.PowerUserMapper;
import com.general.template.pojo.PowerDimension;
import com.general.template.pojo.PowerQuestionPersonality;
import com.general.template.pojo.PowerUser;
import com.general.template.service.PowerDimensionService;
import com.general.template.service.PowerQuestionPersonalityService;
import com.general.template.utils.IdWorker;
import com.general.template.utils.Pages;
import com.general.template.utils.StringUtils;
import com.general.template.vo.QuestionCommonVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.general.template.pojo.PowerQuestionCommon;
import com.general.template.mapper.PowerQuestionCommonMapper;
import com.general.template.service.PowerQuestionCommonService;

/**
 * @Author: 杰哥
 * Date: 2021/2/16 22:39
 * @Description:
 **/

@Service
public class PowerQuestionCommonServiceImpl extends ServiceImpl<PowerQuestionCommonMapper, PowerQuestionCommon> implements PowerQuestionCommonService {

    @Autowired
    private PowerQuestionPersonalityService questionPersonalityService;

    @Autowired
    private PowerDimensionService powerDimensionService;

    @Autowired
    private IdWorker worker;

    @Override
    public int addQuestion(PowerQuestionCommon questionCommon) {
        PowerQuestionCommonMapper mapper = getBaseMapper();
        return mapper.insert(questionCommon);
    }

    @Override
    public Map<String, Object> addList(List<QuestionCommonVo> vo) {
        PowerQuestionCommonMapper mapper = getBaseMapper();
        Map<String, Object> map = new HashMap<>(16);
        long success = 0;
        long fail = 0;
        for (QuestionCommonVo commonVo : vo) {
            if (StringUtils.isNullOrEmpty(commonVo.getQuestionContent())||StringUtils.isNullOrEmpty(commonVo.getQuestionOptions())){
                continue;
            }
            PowerQuestionCommon common = new PowerQuestionCommon();
            common.setId(Long.valueOf(worker.nextId()).toString());
            common.setQuestionType("单选题");
            common.setQuestionContent(commonVo.getQuestionContent());
            common.setInspectionName(commonVo.getInspectionName());
            common.setQuestionMediaName(mapToJson(commonVo.getQuestionMediaName()));
            common.setQuestionMediaUrl(mapToJson(commonVo.getQuestionMediaName()));
            common.setQuestionMediaStatus(commonVo.getQuestionMediaStatus());
            common.setQuestionOptions(mapToJson(commonVo.getQuestionOptions()));
            common.setQuestionOptionScore(mapToJson(commonVo.getQuestionOptionScore()));
            common.setCreateTime(new Date());
            int flat = addQuestion(common);
            if (flat == 0) {
                fail++;
            } else {
                success++;
            }
        }
        map.put("success", success);
        map.put("fail", fail);
        return map;
    }

    @Override
    public Pages<QuestionCommonDto<String>> pageList(Pages<QuestionCommonDto<String>> pages) {
        PowerQuestionCommonMapper mapper = getBaseMapper();
        IPage<PowerQuestionCommon> page = new Page<>(pages.getCurrentPage(), pages.getPageSize());
        QueryWrapper<PowerQuestionCommon> wrapper = new QueryWrapper<>();
        for (Map.Entry<String, Object> entry : pages.getParams().entrySet()) {
            if (!StringUtils.isNullOrEmpty(entry.getValue())){
                if (!"questionContent".equals(entry.getKey())){
                    wrapper.eq(StringUtils.upperCharToUnderLine(entry.getKey()),entry.getValue());
                }else{
                    wrapper.like("question_content","%"+entry.getValue()+"%");
                }
            }
        }
        String desc = "desc";
        if (!StringUtils.isNullOrEmpty(pages.getSortColumn())){
            if (desc.equals(pages.getSortMethod())){
                wrapper.orderByDesc(StringUtils.upperCharToUnderLine(pages.getSortColumn()));
            }else{
                wrapper.orderByAsc(StringUtils.upperCharToUnderLine(pages.getSortColumn()));
            }
        }
        IPage<PowerQuestionCommon> selectPage = mapper.selectPage(page, wrapper);
        List<PowerQuestionCommon> records = selectPage.getRecords();
        List<QuestionCommonDto<String>> dtoList = new ArrayList<>();
        for (PowerQuestionCommon common : records) {
            QuestionCommonDto<String> qc = new QuestionCommonDto<>();
            BeanUtils.copyProperties(common,qc);
            qc.setQuestionOptionScore(JSON.parseArray(common.getQuestionOptionScore(),String.class));
            qc.setQuestionOptions(JSON.parseArray(common.getQuestionOptions(),String.class));
            qc.setQuestionMediaName(JSON.parseArray(common.getQuestionMediaName(),String.class));
            qc.setQuestionMediaUrl(JSON.parseArray(common.getQuestionMediaUrl(),String.class));
            dtoList.add(qc);
        }
        pages.setList(dtoList);
        pages.setTotalCount((int) selectPage.getTotal());
        pages.setTotalPage((int) selectPage.getPages());
        return pages;
    }

    @Override
    public List<QuestionCommonDto> getRandomList(Integer jobId) {
        PowerQuestionCommonMapper mapper = getBaseMapper();
        List<QuestionCommonDto> dtoList = new ArrayList<>();
        QueryWrapper<PowerQuestionCommon> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0);
        List<PowerQuestionCommon> commons = mapper.selectList(wrapper);
        int i2 = commons.size();
        if (i2!=0){
            Set<Integer> random = StringUtils.random(commons.size(), 33);
            for (Integer index : random) {
                PowerQuestionCommon common = commons.get(index);
                QuestionCommonDto<String> dto = new QuestionCommonDto<>();
                BeanUtils.copyProperties(common,dto);
                dto.setQuestionMediaName(JSON.parseArray(common.getQuestionMediaName(),String.class));
                dto.setQuestionMediaUrl(JSON.parseArray(common.getQuestionMediaUrl(),String.class));
                dto.setQuestionOptions(JSON.parseArray(common.getQuestionOptions(),String.class));
                dto.setQuestionOptionScore(JSON.parseArray(common.getQuestionOptionScore(),String.class));
                dtoList.add(dto);
            }
        }
        BaseMapper<PowerDimension> dimensionBaseMapper = powerDimensionService.getBaseMapper();
        List<PowerDimension> dimensionList = dimensionBaseMapper.selectList(new QueryWrapper<PowerDimension>().eq("jobs_id", jobId).eq("status", 0));
        int size = dimensionList.size();
        int number = 20/size;
        int[] array = new int[size];
        for (int i = 0; i < size ; i++) {
            array[i] = number;
        }
        int rand = 20%size;
        if (rand!=0){
            Random dom = new Random();
            for (int i = 0; i < rand ; i++) {
               int index = dom.nextInt(size);
               array[index]++;
            }
        }
        BaseMapper<PowerQuestionPersonality> baseMapper = questionPersonalityService.getBaseMapper();
        for (int i = 0; i < size; i++) {
            QueryWrapper<PowerQuestionPersonality> pwrapper = new QueryWrapper<>();
            pwrapper.eq("jobs_id",jobId);
            pwrapper.eq("status",0);
            pwrapper.eq("dimension_id",dimensionList.get(i).getId());
            List<PowerQuestionPersonality> personalityList = baseMapper.selectList(pwrapper);
            int i1 = personalityList.size();
            if (i1!=0){
                Set<Integer> prandom = StringUtils.random(personalityList.size(), array[i]);
                for (Integer index : prandom) {
                    PowerQuestionPersonality powerPersonality = personalityList.get(index);
                    QuestionCommonDto<String> dto = new QuestionCommonDto<>();
                    BeanUtils.copyProperties(powerPersonality,dto);
                    dto.setQuestionMediaName(JSON.parseArray(powerPersonality.getQuestionMediaName(),String.class));
                    dto.setQuestionOptions(JSON.parseArray(powerPersonality.getQuestionOptions(),String.class));
                    dto.setQuestionMediaUrl(JSON.parseArray(powerPersonality.getQuestionMediaUrl(),String.class));
                    dto.setQuestionOptionScore(JSON.parseArray(powerPersonality.getQuestionOptionScore(),String.class));
                    dtoList.add(dto);
                }
            }
        }
        return dtoList;
    }

    private String mapToJson(String options){
        List<String> optList = Arrays.asList(options.split("，"));
        return JSON.toJSONString(optList);
    }
}

